有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用无序列表计算团队统计数据

我正在做一个体育项目,其中我有一个无序列表,其中包含多个玩家对象。这些球员对象是篮球队的球员,具有球队(字符串)、总得分(int)等属性

我目前正在尝试写一个计算联盟中得分最高的球队的方法。因此,我的列表中有多个球员对象,每个人都有各自的总得分,我试图用这个来计算得分最多的球队

我可以通过在列表中循环找到最高的分值,然后再次循环找到得分=上一个循环中找到的最高分值的球员,轻松计算出得分最多的球员。问题是我不知道如何在整个团队中做到这一点,特别是因为现在所有的积分都必须属于一个团队

谢谢


共 (1) 个答案

  1. # 1 楼答案

    使用地图,可以执行以下操作:

    Map<String, Integer> teamsPoints = new HashMap<String, Integer>();
    for (Player player : players)
    {
        Integer teamPoints = teamsPoints.get(player.getTeamName());
        if (teamPoints == null)
            teamsPoints.put(player.getTeamName(), player.getPoints());
        else
            teamsPoints.put(player.getTeamName(), teamPoints + player.getPoints());
    }
    

    你可以像这样在地图上迭代:

    for (Map.Entry<String, Integer> teamPoints: teamsPoints.entrySet()) 
    {
        System.out.println("Team = " + teamPoints.getKey() + ", Total points= " + teamPoints.getValue());
    }